package com.test.ssm.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradePrecreateModel;
import com.alipay.api.domain.AlipayTradeWapPayModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.test.ssm.pojo.HotelOrder;
import com.test.ssm.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @author 徒有琴
 */
@Controller
public class AlipayConroller {
    static String APP_ID = "2016080600178939";
    static String CHARSET = "utf-8";
    static String APP_PRIVATE_KEY = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDJjPbmpVMEaU+l" +
            "cgsLK0sOy88nvxdVH3xRxUPdhrX/Y22MIb8sZiD4z5ZyJw6pi295Uh7gYvMX1c8+" +
            "FmoD8Lv/k9+pO33aAoDGvOQP62EieRtNwLQWZBDuTLG63GdhhgBxDUPCnfQXiphQ" +
            "r/TXtLiJhmy25yuvc9DbKv8glDRveKO/gdOYerJH5aMdokWLXBpn5AZOOUZi6YNa" +
            "94wRePrtxVMhvXaP/epr60kKy1HDmNQjVYuXME3P4uwYnbdktaJE9dTDSpv1Voh9" +
            "CDJprhGbWZVJcctjO7O3oFDhpSbEIaMmh3g2tiqcRsLQKrovkoP9Zvcz56OeI6hz" +
            "6vo6EdR1AgMBAAECggEBALUm1eOIRI16efOiBPsM9nFeDdsTjc0cd4inXNAG/B2H" +
            "KDcDPeiSAqCfNAF1yV/py0+n18imJwgNTC/pxW+1N8QHDMf2iK8iAMyfifwk+zEY" +
            "2MmRoktdtTn6BOSGpQSqhEsYOQb7ISDnmO8st0wJSrOQ9rWOIV2ZIudaReTqUBa/" +
            "J0VNe3Yv8cG9sawvkgOGXWv0OeIkpHU+kzUbzt4h4a8D7xzjAk57RpLAy+FDvB4p" +
            "Yr7VybnW4Y0DGkTmHMmloCvOQveaO7lAy+ZIeVQ7u9mlPYSFmhowblr5ROs400so" +
            "P3J5HsY8GHl/0v/m2C1tEp1SwfunyBHoQJAvjFYqyiECgYEA585Z9RwgPg2H1YZ4" +
            "S8vCUImICofQlcxKmno22ICi9jlWQYT6SsMwMEAvfm8RSDiAj85RXxrWupiSZMu2" +
            "K1NpExczOr2r5AD+lu9RdiW3DC3J9+PUWXnj1ZJfC2ea6sU9LImdJ/ku6ePYh5Av" +
            "wk5xGfi0P7t+Xff0YW+o8yZOsGsCgYEA3pY3MtpRT2ahB8jgnzuVVYX4hTjEzCbK" +
            "0fv7D3NHkqkTLxeo2tpE/uqmWGKRrrhN+u9Z4CLIpT505kDExXinttfjkUUD2HKj" +
            "OsenXpQwP+t8zwnh4A8OVIRq9Y8wYbykpuT839Y4BWp6fDLUccs0Ho94abwqz8/E" +
            "Lg0NySofRp8CgYA8QNP7NVtgJc43/2MHeKhCnO0ip5jdRyPhMYFOF2nEjLTSBQm2" +
            "IzREZnqx55bbaexo9N0L1oMYL45l6tmoO18lmjMzwpeKhYOnof9PsY/593D3IV5R" +
            "/6/sFMblxQFsouY6zG5wNIIwQ4xF+IGhhRg7Av1/T3ISZOA973M/+KYdjwKBgHpQ" +
            "9fhd/Hyzmx4aB0W5inC69DzRW2QMlTwbSnXNFbHEc6RXThUmCPBEpjC/yerHoSKa" +
            "UTtYIgacccTuJrOVgCR8MrPrxxc0t/pfKNxSdslJcQadGaD05R0Qv249x4qODbUg" +
            "9M1UfOiNAM4raI836WY51SPVoXkdZWMhDUhUe2dlAoGADskPZbXjSWLbscPzru6f" +
            "TNgijRWJlkkgN5SYrppXE2VsWM4hnNv8wS+LqRNoehvbA3uDyut2QvUre71RBQ/+" +
            "5WZRXVqXAuvE6ep619sn+PM7a/eB9Ru1Cmu319YvBUIOZ+2wBYZAANp6w4iAXjXD" +
            "lkc4z6xPND19Y10XFIZ2n3g=";

    //app
    public static void main(String[] args) throws Exception {
        AlipayClient alipayClient = new DefaultAlipayClient(
                "https://openapi.alipaydev.com/gateway.do",
                APP_ID, APP_PRIVATE_KEY, "json", CHARSET, AlipayConfig.ALIPAY_PUBLIC_KEY, "RSA");
        AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();
        AlipayTradePrecreateModel model = new AlipayTradePrecreateModel();
        request.setBizModel(model);
        model.setOutTradeNo(System.currentTimeMillis() + "");
        model.setTotalAmount("88.88");
        model.setSubject("Iphone6 16G");
        AlipayTradePrecreateResponse response = alipayClient.execute(request);
        System.out.print(response.getBody());
        System.out.print(response.getQrCode());
    }

    @Autowired
    private OrderService orderService;

    @RequestMapping("alipay.html")
    public void alipay(HttpServletRequest request, HttpServletResponse response, Integer id) throws Exception {
        HotelOrder order = orderService.getOrderById(id);
        // 商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = order.getOrderNum();
        // 订单名称，必填
        String subject = "hellojava";
        // 付款金额，必填
        String total_amount = order.getPrice().toString();
        // 商品描述，可空
        //   String body = "";
        // 超时时间 可空
        //  String timeout_express = "2m";
        // 销售产品码 必填
        String product_code = "QUICK_WAP_WAY";
        /**********************/
        // SDK 公共请求类，包含公共请求参数，以及封装了签名与验签，开发者无需关注签名与验签
        //调用RSA签名方式
        AlipayClient client = new DefaultAlipayClient(AlipayConfig.URL, AlipayConfig.APPID, AlipayConfig.RSA_PRIVATE_KEY, AlipayConfig.FORMAT, AlipayConfig.CHARSET, AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.SIGNTYPE);
        AlipayTradeWapPayRequest alipay_request = new AlipayTradeWapPayRequest();

        // 封装请求支付信息
        AlipayTradeWapPayModel model = new AlipayTradeWapPayModel();
        model.setOutTradeNo(out_trade_no);
        model.setSubject(subject);
        model.setTotalAmount(total_amount);
//        model.setBody(body);
//        model.setTimeoutExpress(timeout_express);
        model.setProductCode(product_code);
        alipay_request.setBizModel(model);
        // 设置异步通知地址
        alipay_request.setNotifyUrl(AlipayConfig.notify_url);
        // 设置同步地址
        alipay_request.setReturnUrl(AlipayConfig.return_url);

        // form表单生产
        String form = "";
        try {
            // 调用SDK生成表单
            form = client.pageExecute(alipay_request).getBody();
            response.setContentType("text/html;charset=" + AlipayConfig.CHARSET);
            response.getWriter().write(form);//直接将完整的表单html输出到页面
            response.getWriter().flush();
            response.getWriter().close();
        } catch (AlipayApiException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    @RequestMapping("return.html")
    public String r(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //获取支付宝GET过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
           // valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }

        //获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以下仅供参考)//
        //商户订单号

        String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");

        //支付宝交易号

        String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");

        //获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以上仅供参考)//
        //计算得出通知验证结果
        //boolean AlipaySignature.rsaCheckV1(Map<String, String> params, String publicKey, String charset, String sign_type)
        boolean verify_result = AlipaySignature.rsaCheckV1(params, AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.CHARSET, "RSA2");

        if (verify_result) {//验证成功
            //////////////////////////////////////////////////////////////////////////////////////////
            //请在这里加上商户的业务逻辑程序代码
            //该页面可做页面美工编辑
            System.out.println("成功");
            //////////////////////////////////////////////////////////////////////////////////////////
        } else {
            System.out.println("失败");
        }
        return "success";
    }

    @RequestMapping("callback.html")
    public void callback(HttpServletRequest request, HttpServletResponse response) throws Exception {
        System.out.println("callback");
        PrintWriter out = response.getWriter();
//获取支付宝POST过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
            params.put(name, valueStr);
        }
        //获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以下仅供参考)//
        //商户订单号
        System.out.println(params);
        String out_trade_no = request.getParameter("out_trade_no");
        //支付宝交易号

        String trade_no = request.getParameter("trade_no");

        //交易状态
        String trade_status = request.getParameter("trade_status");

        //获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以上仅供参考)//
        //计算得出通知验证结果
        //boolean AlipaySignature.rsaCheckV1(Map<String, String> params, String publicKey, String charset, String sign_type)
        boolean verify_result = AlipaySignature.rsaCheckV1(params, AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.CHARSET, AlipayConfig.SIGNTYPE);

        if (verify_result) {//验证成功
            //////////////////////////////////////////////////////////////////////////////////////////
            //请在这里加上商户的业务逻辑程序代码
            HotelOrder order = orderService.getOrderByNum(out_trade_no);
            if (order != null && order.getStatus() == 0) {//未支付

                //——请根据您的业务逻辑来编写程序（以下代码仅作参考）——

                if (trade_status.equals("TRADE_FINISHED")) {
                    //判断该笔订单是否在商户网站中已经做过处理
                    //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                    //请务必判断请求时的total_fee、seller_id与通知时获取的total_fee、seller_id为一致的
                    //如果有做过处理，不执行商户的业务程序

                    //注意：
                    //如果签约的是可退款协议，退款日期超过可退款期限后（如三个月可退款），支付宝系统发送该交易状态通知
                    //如果没有签约可退款协议，那么付款完成后，支付宝系统发送该交易状态通知。
                } else if (trade_status.equals("TRADE_SUCCESS")) {
                    //判断该笔订单是否在商户网站中已经做过处理
                    //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                    //请务必判断请求时的total_fee、seller_id与通知时获取的total_fee、seller_id为一致的
                    //如果有做过处理，不执行商户的业务程序
                    order.setStatus(1);
                    //注意：
                    //如果签约的是可退款协议，那么付款完成后，支付宝系统发送该交易状态通知。
                } else {
                    order.setStatus(-1);
                }
                order.setTradeNum(trade_no);
                order.setPayTime(new Date());
                order.setCallback(trade_status);
                orderService.updateOrder(order);
            }
            //——请根据您的业务逻辑来编写程序（以上代码仅作参考）——
            out.println("success");    //请不要修改或删除

            //////////////////////////////////////////////////////////////////////////////////////////
        } else {//验证失败
            System.out.println("签名失败");
            out.println("fail");
        }
    }
}
